<template>
	<view>
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<!-- <view class="cu-bar search" style="padding: 10px">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描商品" :show-action="false"
				@search="confirm"></u-search>
			
		</view> -->
		<u-popup v-model="show" mode="right" length="90%">
			<!-- class="form"  -->
			<u-form class="form" style="padding: 0 10px;" :model="query" ref="uForm" label-position="left">
				
				<view style="" class="text-border">
					<view class="text text-lg text-green">基本信息</view>
					<u-form-item label="公司:" prop="companyName" label-width="230">
						<js-select v-model="query.companyCode" :showFilter="false" :items="companySelectList"  placeholder="请选择" :tree="true"
							:label-value="query['company.companyName']" @label-input="query['company.companyName'] = $event"></js-select>
					</u-form-item>
				
					<u-form-item  label="商品名称:" prop="invName" label-width="230">
						<u-input placeholder="请输入" v-model="query['invName']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item  label="形象刊:" prop="cfree1" label-width="230">
						<u-input placeholder="请输入" v-model="query['cfree1']" type="text" maxlength="200"></u-input>
					</u-form-item>
				</view>
			</u-form>
			<!-- <view class="footer">
			<u-button class="btn" type="primary" @click="submit">查询</u-button>
		</view> -->
			<view class="cu-bar"></view>
			<view class=" flex cu-bar tabbar bg-white foot cu-modal-footer">
				<!-- round -->
				<button class="cu-btn  lines-red lg " @click="reset">重置</button>
				<button class="cu-btn  bg-confirm lg margin-left " @click="submit">查询</button>
			</view>
		</u-popup>
		
		<scroll-view scroll-y="true" @scrolltolower="loadMore" :refresher-enabled="true" :scrolltolower-enabled="true"
			:refresher-triggered="triggered" @refresherrefresh="refresherrefresh" @scrolltoupper="refresherrefresh"
			class="scroll-view-class" :style="{ height: computedScrollViewHeight }">
			<view class="scroll-content" ref="scrollContent" style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        " :style="{ height: computedScrollViewHeight  }">
				<view v-for="(item,index) in list"  class="cu-item shadow " style="position: relative;margin-bottom: 10px;" :key="item.id">
					<view class="cu-form-group"  style="display: flex;justify-content: space-between;">
						<view
							style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;min-width: 40px;text-align: center;font-style: italic;font-weight: bold">
							{{ index + 1 }}
						</view>
						<view class="">
							<dictLabel
								style="margin-left: 10px;"
								:value="item.jhStatus"
								dict-type="jh_main_status"
								ref="dictLabel"
								:key="`dictLabel_${item.id}_${item.jhStatus}`">
							</dictLabel>
						</view>
					</view>
					<view class="cu-form-group">
						<view class="title">商品编码：</view>
						<view style="flex: 1;"> {{ item.basInv && 	item.basInv.viewCode|| ""  }} </view>
					</view>
					<view class="cu-form-group">
						<view class="title">商品名称：</view>
						<view style="flex: 1;"> {{ item.basInv && 	item.basInv.invName|| ""  }} </view>
					</view>
					<view class="cu-form-group">
						<view class="title">货位：</view>
						<view style="flex: 1;"> {{ item.cposNames || ""  }} </view>
					</view>
					<!--  -->
					
					<view class="cu-form-group" style="font-weight: bold;">
						<view class="title">拣货总数：</view>
						<view style="flex: 1;"> {{ item.fqty|| ""  }} </view>
						<view class="title">已拣货数：</view>
						<view style="flex: 1;"> {{ item.sumJhQty|| ""  }} </view>
					</view>
					<!-- <view class="cu-form-group">
						<view class="title">货位：</view>
						<view style="flex: 1;"> {{ item.sumQty|| ""  }} </view>
					</view> -->
					<view  class="cu-form-group" >
						<view class="">
						</view>
						<view class="">
							<button  class="cu-btn lines-green shadow-blur" @click="toForm(item)">
								<!-- 确认拣货 -->
								{{ item.jhStatus == 2 ? '退回' : '确认拣货' }}
							</button>
						</view>
					</view>
				
				</view>

				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 80vh;"></u-empty>
			</view>
		</scroll-view>
		<!-- <view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="handleFocus" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view >扫一扫</view>
						</view>
					</u-button>
					
				</movable-view>
			</movable-area>
		</view> -->
	</view>
</template>
<script>
	import dictLabel from "@/components/dictLabel.vue";
	export default {
		components: {
			dictLabel,
		},
		data() {
			return {
				x: 650, //x坐标
				y: 650, //y坐标
				companySelectList:[],
				show: false,
				smshow: false,
				focus: false,
				barCode: "",
				remarks: '',
				czData: {},
				show2: false,
				type: 'text',
				startTime: false, //控制日期显示
				endTime: false, //控制日期显示
				show: false,
				inputStyle: {
					fontSize: '34rpx'
				},
				filterIcon: "/static/image/filter.png",
				keyword: "",
				background: {
					backgroundColor: '#3E97B0',
				},
				list: [],
				itemContent: {},
				loadStatus: "loadmore",
				triggered: false,
				flag: false,
				scrollViewHeight: 0,
				headerHeight: 0,
				djno:'',
				query:{
					pageNo: 1,
					pageSize: 5,
				}
			};
		},
		onShow() {
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			console.log('onShow');
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			this.$u.api.ktnw.companyTreeData().then(res => {
				this.companySelectList = res;
			});

			// 优化：只在必要时重新加载数据和更新组件
			setTimeout(()=>{
				this.loadData().then(() => {
					// 只有当数据加载完成且列表有数据时，才更新dictLabel组件
					if (this.list && this.list.length > 0) {
						this.$nextTick(() => {
							// 延迟更新，避免频繁调用
							setTimeout(() => {
								this.forceUpdateDictLabels();
							}, 200);
						});
					}
				});
			}, 50);

			this.focus = false;
			setTimeout(() => {
				this.focus = true;
			}, 500)
		},
		onLoad(e) {
			this.query.djno = e.djno
			this.query.pageNo = 1;
			this.loadData();
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		mounted() {
			this.calculateScrollViewHeight();
		},
		computed: {
			computedScrollViewHeight() {
				return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
			},
		},
		methods: {
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.barCode = ''
					_that.focus = true;
				}, 500)
			},
			invCode(bar, companyCode) {
				let InventoryPrefix = this.vuex_config.InventoryPrefix;
				if (bar.indexOf(InventoryPrefix) != -1) {
					return bar
				} else {
					let code = `inv_${companyCode}_${bar}`
					return code
				}
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code
				
				//判断条形码长度是否大于3
				if(barcode.length > 3){
					//去除换行符
					let newString = barcode.replace('\n;', '');
					
					this.barCode = newString;
					this.confirm()
					//将换行符分割成数组
					// const allItems = newString.split('\n');
					// 	//遍历数组，将每一项添加到arr中
					// 	for(let i = 0;i<allItems.length;i++){
					// 		this.arr.push({
					// 			"content":allItems[i],
					// 			"remarks":this.remarks
					// 		})
					// 	}
				}
			},
			confirm() {
				let _that = this;
				if (this.barCode) {
					let bar = encodeURIComponent(this.barCode)
					let InvBarType = _that.vuex_config.InvBarType;
					
					let barCode = this.invCode(bar, this.list[0].parent.companyCode)
					let data = {
						...this.query,
						pageNo:1
					}
					this.$u.api.ktnw.getBarInfo({
						barCode: barCode,
						barType: InvBarType,
						companyCode: this.list[0].parent.companyCode
					}).then((res) => {
						if(res.result == 'true'){
							data.invCode = res.data.basInv?.invCode
							data.invName = res.data.basInv?.invName
							// _that.handleFocus()
							setTimeout(()=>{
								this.barCode = ''
							},500)
							_that.$u.api.ktnw.listDataJhDetails(data).then((res) => {
								if (res.list.length == 1) {
									_that.sendMp3('cg');
									uni.$off('xwscan', this.BroadcastScanningToObtainData)
									uni.navigateTo({
										url: '/pages/ktnw/jh/form?id=' + res.list[0].id
									})
								}else{
									_that.sendMp3('sb');
									_that.$refs.jsError.showError("", "请扫描对应的商品条码！", "warn");
								}
							});
						}else{
							_that.handleFocus()
							_that.sendMp3('sb');
							let message = res.message
							_that.$refs.jsError.showError("", message, "error");
						}
						
					})
				} else {
					_that.handleFocus()
					// this.$u.toast("任务单号不能为空!");
					_that.$refs.jsError.showError("", "请扫描正确的商品条码", "warn");
				}
			},
			search() {
				let _that = this;
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: function(res) {
						console.log("条码类型：" + res.scanType);
						console.log("条码内容：" + res.result);
						_that.barCode = res.result;
						_that.confirm()
					},
				});
			},
			
		
			toForm(item){
				uni.$off('xwscan', this.BroadcastScanningToObtainData)
				uni.navigateTo({
					url: '/pages/ktnw/jh/form?id=' + item.id,
				})
			},
			reset() {
				this.list = [];
				this.query = {
					pageNo: 1,
					pageSize: 20,
				};
				this.loadData();
				this.show = false
			},
			submit() {
				this.list = [];
				this.query.pageNo = 1;
				this.loadData();
				this.show = false
			},
			startConfirm(e) {
				this.query.planArrDate_gte = e.year + '-' + e.month + '-' + e.day;
			},
			endConfirm(e) {
				this.query.planArrDate_lte = e.year + '-' + e.month + '-' + e.day;
			},
			customBack() {
				// 跳转到工作台页面
				uni.navigateBack({
					delta: 1,
				});
			},
			async calculateScrollViewHeight() {
				try {
					// 等待头部高度计算完成
					// this.headerHeight = 52
					this.headerHeight = 0
					// 计算tabBar高度
					if (this.flag) {
						this.tabBarHeight = 60; // 假设tabbar高度为50px，实际应根据实际情况获取
					} else {
						this.tabBarHeight = 0;
					}
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
				} catch (error) {
					console.error('Error while calculating ScrollView height:', error);
				}
			},
			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.pageNo += 1;
					this.loadData("add");
				}, 100);
			},
			loadData(type) {
				// 返回 Promise 以支持 await
				return this.$u.api.ktnw.listDataJhDetails(this.query).then((res) => {
					if (res.list.length >= 0) {
						// this.xmList = res.list
						if (res.list.length < 20 || res.list.length == 0) {
							this.loadStatus = "nomore";
						}
						var data = res.list;
						if (type == "add") {
							for (var i = 0; i < data.length; i++) {
								this.list.push(data[i]);
							}
						} else {
							this.list = data;
						}
					}
					return res;
				});
			},
			// 强制更新所有dictLabel组件的方法
			forceUpdateDictLabels() {
				console.log('forceUpdateDictLabels called');
				// 通过refs强制更新dictLabel组件
				if (this.$refs.dictLabel) {
					if (Array.isArray(this.$refs.dictLabel)) {
						console.log('Updating', this.$refs.dictLabel.length, 'dictLabel components');
						this.$refs.dictLabel.forEach((ref, index) => {
							if (ref && ref.debouncedLoadData) {
								// 使用防抖方法而不是直接调用loadData
								setTimeout(() => {
									ref.debouncedLoadData();
								}, index * 50); // 错开执行时间
							}
						});
					} else {
						if (this.$refs.dictLabel.debouncedLoadData) {
							this.$refs.dictLabel.debouncedLoadData();
						}
					}
				}
			},

			async refresherrefresh() {
				this.triggered = true;
				this.query.pageNo = 1;
				await this.loadData();
				const scrollTop = 0
				uni.pageScrollTo({
					scrollTop,
					duration: 0,
				});
				setTimeout(() => {
					this.triggered = false;
					// 刷新完成后，只有在有数据时才更新dictLabel组件
					if (this.list && this.list.length > 0) {
						this.forceUpdateDictLabels();
					}
				}, 500);
			},
		},
		// beforeDestroy() {
		// 	// 清理事件监听器
		// 	try {
		// 		this.$refs.xmInfo.$off('child-mounted-done');
		// 	} catch (e) {
		// 		console.log('Error while unbinding event:', e);
		// 	}
		// }
	};
</script>
<style lang="scss" scoped>
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
	
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
	
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	.text-border{
		border:2px solid  rgb(170, 170, 170); 
		border-radius: 5px;
		position: relative;
		padding-top: 20rpx;
		margin-top: 40rpx;
		padding-left: 20rpx;
		.text{
			position: absolute;
			background-color: #fff;
			padding: 10rpx 10rpx;
			top: -25rpx;
			right: 30rpx;
		}
	}
	/* .custom-style{
		background-color: rgba(25, 190, 107, 0.7);
	} */
	.text-xxl{
		font-size:60rpx;
	}
	.cu-bar {
		min-height: 60px;
	}
	
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}
	
	.foot {
		background: #fff;
	}
	
	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}
	
	.title {
		width: 210rpx;
	}
	
	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}
	
	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}
	
	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
</style>